package com.lee.security.provider.validate.sms;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lee.security.properties.SecurityConstants;
import com.lee.security.provider.validate.ValidateCode;
import com.lee.security.provider.validate.ValidateCodeGenerator;
import com.lee.security.provider.validate.ValidateCodeType;
import com.lee.security.provider.validate.impl.AbstractValidateCodeProcessor;
import com.lee.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletResponse;

/**
 * 短信验证码处理器
 *
 * @author Lee
 * @date 2018年6月1日
 */
@Component
public class SmsCodeProcessor extends AbstractValidateCodeProcessor {

    /**
     * 短信验证码发送器
     */
    @Autowired
    private SmsCodeSender smsCodeSender;

    @Autowired
    private ValidateCodeGenerator smsCodeGenerator;

    @Autowired
    private ObjectMapper objectMapper;

    private String mobileParameter = SecurityConstants.DEFAULT_PARAMETER_NAME_USERNAME;

    @Override
    protected void send(ServletWebRequest request, ValidateCode validateCode) throws Exception {
        String mobile = ServletRequestUtils.getRequiredStringParameter(request.getRequest(), mobileParameter);
        String scene = String.valueOf(
                request.getAttribute(SecurityConstants.DEFAULT_PARAMETER_NAME_SCENE, RequestAttributes.SCOPE_REQUEST));

        smsCodeSender.sendCode(mobile, scene, validateCode.getCode());
        HttpServletResponse response = request.getResponse();
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.getWriter().write(objectMapper.writeValueAsString(ResponseVO.success()));
    }

    @Override
    protected ValidateCodeType getValidateCodeType() {
        return ValidateCodeType.sms;
    }

    @Override
    protected ValidateCode generate(ServletWebRequest request) {
        return smsCodeGenerator.generate(request);
    }

}
